/*
 * MessageCS2LSRep.cpp
 *
 *  Created on: Nov 14, 2010
 *      Author: nobal
 */

#include "MessageChunkInfo.h"
#include <cstring>

MessageChunkInfo::MessageChunkInfo(string msgtype) {
	this->messageType=msgtype;
}

MessageChunkInfo::MessageChunkInfo(string msgtype,string msg):Message(msg,msgtype){

}

MessageChunkInfo::MessageChunkInfo(std::vector<string> chunks,string msgtype){
	string msg=this->getMessageFromChunks(chunks);
	this->chunks=chunks;
	this->message=msg;
	this->messageType=msgtype;
}

MessageChunkInfo::~MessageChunkInfo() {
	// TODO Auto-generated destructor stub
}

//takes array of IP:PORT:fileChunk
//and generates message (a string) of IP:PORT:fileChunk|IP:PORT:fileChunk
void MessageChunkInfo::setChunks(std::vector<string> chunks){
	this->chunks=chunks;
}
/** Must set message type when this function is called. */
void MessageChunkInfo::buildMessage(){
	string msg= this->getMessageFromChunks(this->getChunks());
	this->message=msg;
}

std::vector<string> MessageChunkInfo::getChunks(){
	return this->chunks;
}

string MessageChunkInfo::getMessageFromChunks(std::vector<string> chunks){
		string msg="";
		int i=0;
		for(vector<string>::const_iterator it = chunks.begin(); it != chunks.end(); ++it){
			if(i<=(int)chunks.size()-2){
				msg+=chunks[i]+MSG_SEPARATOR;
			}
			else{
				msg+=chunks[i];
			}
			i++;
		}
		return msg;
}
// Generate chunks from raw message. The raw message will be in the form
// MSGTYPE|IP:PORT:fileChunk|IP:PORT:fileChunk
// It returns a vector of MSGTYPE|IP:PORT
std::vector<string> MessageChunkInfo::setChunksFromRawMsg(string rawMsg){
	string msgType;
	string msgPart;
	std::vector<string> chunks;
	if(!rawMsg.empty()){
			int pos1=rawMsg.find(MSG_SEPARATOR);
			msgType=rawMsg.substr(0,pos1);

			//msgPart= IP:PORT:fileChunk|IP:PORT:fileChunk
			msgPart=rawMsg.substr(pos1+1,rawMsg.length()- pos1);

			// Skip delimiters at beginning.
			string::size_type lastPos = msgPart.find_first_not_of(MSG_SEPARATOR, 0);
			// Find first "non-delimiter".
			string::size_type pos= msgPart.find_first_of(MSG_SEPARATOR, lastPos);
		    while (string::npos != pos || string::npos != lastPos){
			        // Found a token, add it to the vector.
			    	chunks.push_back(msgPart.substr(lastPos, pos - lastPos));
			        // Skip delimiters.  Note the "not_of"
			        lastPos = msgPart.find_first_not_of(MSG_SEPARATOR, pos);
			        // Find next "non-delimiter"
			        pos = msgPart.find_first_of(MSG_SEPARATOR, lastPos);
			 }

	}
	this->chunks=chunks;
	setMessage(this->getMessageFromChunks(this->chunks));
	return chunks;
}

